package com.lifei.service;

import com.lifei.domain.Order;
import com.lifei.domain.Product;
import com.lifei.repository.OrderRepository;
import com.lifei.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expireKey = message.toString();

        if (expireKey.startsWith("order:")){

            Integer orderId = Integer.valueOf(expireKey.replace("order:",""));

            Order order = orderRepository.findOneById(orderId);
            order.setOrderStatus(2);
            order = orderRepository.save(order);
            System.out.println("... 订单失效，库存还原+1 ...");

            Product product = productRepository.findOneById(order.getProductId());
            product.setNumber(product.getNumber() + 1);
            productRepository.save(product);

            redisTemplate.opsForValue().increment("num");

        }
    }
}
